#!/bin/bash
# Harbor配额告警脚本 - 支持邮件告警

HARBOR_URL="harbor.zx"
THRESHOLD=80  # 告警阈值80%

# 邮件配置，参数自行补充
SMTP_SERVER=""
SMTP_PORT=465
MAIL_FROM=""
MAIL_TO=""
SMTP_USERNAME=""
SMTP_PASSWORD=""
SMTP_USE_TLS=true
SMTP_OPPORTUNISTIC_TLS=false

check_all_quotas() {
  # 获取所有项目配额
  QUOTAS=$(curl -s -k -X GET "https://${HARBOR_URL}/api/v2.0/quotas" \
    -H "Authorization: Basic $(echo -n admin:Harbor12345 | base64)")

  echo "$QUOTAS" | jq -r '.[] | @base64' | while read quota; do
    PROJECT_DATA=$(echo $quota | base64 -d)

    PROJECT_NAME=$(echo $PROJECT_DATA | jq -r '.ref.name')
    STORAGE_USED=$(echo $PROJECT_DATA | jq -r '.used.storage')
    STORAGE_LIMIT=$(echo $PROJECT_DATA | jq -r '.hard.storage')

    if [ "$STORAGE_LIMIT" != "-1" ] && [ "$STORAGE_LIMIT" != "null" ]; then
      USAGE_PERCENT=$(echo "scale=2; $STORAGE_USED * 100 / $STORAGE_LIMIT" | bc)

      if (( $(echo "$USAGE_PERCENT > $THRESHOLD" | bc -l) )); then
        # 发送告警
        send_alert "$PROJECT_NAME" "$USAGE_PERCENT"
      fi
    fi
  done
}

send_email_alert() {
  local project=$1
  local usage=$2

  SUBJECT="Harbor配额告警: 项目 ${project} 存储使用率达到 ${usage}%"
  BODY="项目名称: ${project}\n存储使用率: ${usage}%\n时间: $(date)\n\n请及时处理"

  # 使用TLS加密发送
  sendemail -f "$MAIL_FROM" -t "$MAIL_TO" -u "$SUBJECT" -m "$BODY" \
    -s "$SMTP_SERVER:$SMTP_PORT" -xu "$SMTP_USERNAME" -xp "$SMTP_PASSWORD" \
    -o tls=$SMTP_USE_TLS -o opportunistic-tls=$SMTP_OPPORTUNISTIC_TLS
}

# 执行检查
check_all_quotas